package com.example.demo.web;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/v1/api/threadinfo")
public class ThreadInfoController {

    @Autowired
    private ObjectMapper objectMapper ;
    private static  final ThreadMXBean threadMXBean =  ManagementFactory.getThreadMXBean();

    @GetMapping
    public String stack() throws JsonProcessingException {
        /**
         *  获取当前线程的信息
         */
       ThreadInfo [] threadInfos = threadMXBean.dumpAllThreads(true,true);
       List<String> list = new ArrayList<>();
        for(ThreadInfo info : threadInfos) {
            list.add(objectMapper.writeValueAsString(info));
        }
        SystemInfo si = new SystemInfo();
        HardwareAbstractionLayer hal = si.getHardware();
        OperatingSystem os = si.getOperatingSystem();
      String json =   String.join("<br/><br/><br/><br/>",list);
        List<OSProcess> procs = Arrays.asList(os.getProcesses(5, OperatingSystem.ProcessSort.CPU));
        json = json.concat("<br/><br/><br/><br/>   PID  %CPU %MEM       VSZ       RSS Name");
        for (int i = 0; i < procs.size() && i < 5; i++) {
            OSProcess p = procs.get(i);
            json = json.concat("<br/><br/><br/><br/>" + String.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),
                    100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
                    100d * p.getResidentSetSize() / hal.getMemory().getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
                    FormatUtil.formatBytes(p.getResidentSetSize()), p.getName()));
        }
        return  json;
    }

}
